/**
 * ChartCellChooserFrame.java
 */
package com.pluginsacceptor.plugin.chart;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.awt.Rectangle;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

import org.apache.log4j.Logger;

import com.pluginsacceptor.plugin.chart.model.ChartState;
import com.pluginsacceptor.plugin.chart.model.CurrentChartState;

/**
 * The class create frame for choice cell from spread sheet
 */
public class ChartCellChooserFrame extends JFrame {

    /** */
    private static final long serialVersionUID = 8737495130045187728L;

    /** Logger */
    private static final Logger LOG = Logger.getLogger(ChartCellChooserFrame.class);

    /** */
    private final List<CurrentChartState> chartState;

    /** */
    private final JTextField textField;

    /**
     * Constructor
     */
    public ChartCellChooserFrame(final List<CurrentChartState> chartState)
            throws HeadlessException {

        super();
        setPreferredSize(new Dimension(300, 70));
        this.chartState = chartState;
        this.textField = new JTextField("[]");
        final JButton button = new JButton("ok");
        button.addMouseListener(
                new java.awt.event.MouseAdapter() {
                    @Override
                    public void mouseClicked(final java.awt.event.MouseEvent e) {
                        getActiveChart().setChartState(ChartState.WAIT_UPDATE_DATA);
                        ChartCellChooserFrame.this.setVisible(false);
                        LOG.info("New state " + getActiveChart().getChartState().name());
                    }
                }
                );

        this.add(textField, BorderLayout.CENTER);
        this.add(button, BorderLayout.EAST);
        this.setTitle("Data chooser");
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        this.pack();
        final Rectangle parentBounds = getBounds();
        this.setLocation(
                (int) (parentBounds.getX() + 400),
                (int) (parentBounds.getY() + 400));
        this.setVisible(false);
        this.setAlwaysOnTop(true);
    }

    /**
     * Get active chart == last chart
     * @return active chart
     */
    private CurrentChartState getActiveChart() {
        return chartState.get(chartState.size() - 1);
    }

    /**
     * @return observer for text field changes
     */
    public Observer getObserver() {
        return new Observer() {

            @Override
            public void update(final Observable o, final Object arg) {
                if (ChartCellChooserFrame.this.isVisible()) {
                    textField.setText(getActiveChart().getBarChartData().getAffectedCell());
                }
            }
        };
    }
}
